﻿using System.Collections;
using System.Collections.Generic;
using TTGameEngine;
using UnityEngine;

/// <summary>
/// 为了控制sprite2D对象的层次。将对象的z等同于y值，然后系统会根据z值排序。前提是sortlayer和orderInLayer值相同。
/// sortlayer > orderInLayer > Z > 工程位置靠上的先画 > 后显示（Enabled）的后画
/// </summary>
[ExecuteInEditMode]
public class UpdateSpriteZ : MonoBehaviour {
    public bool m_UpdateSpriteZ = false;
    public bool Debug_DrawZLine = false;
    [SerializeField, ReadOnly]
    public LayerZ[] layerZs = null;
    Transform tf;
    // Use this for initialization
    void Awake() {
        tf = this.transform;
    }

    // Update is called once per frame
    //[ExecuteInEditMode]
    void Update() {
        if(m_UpdateSpriteZ) {
            updateSpriteZ();
        }
    }

    //mark:youhua 不需要每帧检测。有些静态对象，只检测一次。
    void updateSpriteZ() {
#if Unity_EDITOR
        if(tf == null) tf = this.transform;
#endif
        CheckSpriteZ(tf, 0f);
        if(layerZs == null) return;

        for(int i = 0; i < layerZs.Length; i++) {
            LayerZ layerz = layerZs[i];
            Transform layerzTF = layerz.transform;
            if (layerz.m_LayerZBindTF == null) {                
                CheckSpriteZ(layerzTF, layerz.offsetZ);
            } else {
                Vector3 pos = layerzTF.position;
                pos.z = layerz.m_LayerZBindTF.position.z + layerz.m_OrdingInZBind * -0.0001f;
                layerzTF.position = pos;
            }
        }
    }

    void CheckSpriteZ(Transform tf, float offsetZ) {
        Vector3 pos = tf.position;
        pos.z = pos.y + offsetZ;
        tf.position = pos;
    }

    private void OnDrawGizmos() {
        if(Debug_DrawZLine) {
            //显示对象的Z值。
            for(int i = 0; i < layerZs.Length; i++) {
                Transform layerzTF = layerZs[i].transform;
                Vector3 pos = layerzTF.position;
                Vector3 startpos = new Vector3(pos.x - 0.25f, pos.z, pos.z);
                Vector3 endpos = new Vector3(pos.x + 0.25f, pos.z, pos.z);
                Debug.DrawLine(startpos, endpos, Color.yellow);
            }
        }

    }

}
